import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入组件
// import Reg from '@/views/Reg/Reg.vue'
// import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/UserInfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import ArtList from '@/views/Menus/Article/ArtList.vue'
// const Reg = () => import('@/views/Reg/Reg.vue')
// const Login = () => import('@/views/Login/Login.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(/* webpackChunkName: "Reg" */location) {
  return originalPush.call(this, location).catch(err => err)
}

// 声明路由规则
const routes = [
  { path: '/reg', component: () => import(/* webpackChunkName: "Reg" */ '@/views/Reg/Reg.vue') },
  { path: '/login', component: () => import(/* webpackChunkName: "Login" */ '@/views/Login/Login.vue') },
  {
    path: '/',
    redirect: '/home',
    component: Main,
    children: [
      // 首页的子路由规则
      { path: 'home', component: Home },
      // 基本资料的子路由规则
      { path: 'user-info', component: UserInfo },
      // 更换头像的子路由规则
      { path: 'user-avatar', component: UserAvatar },
      // 重置密码的子路由规则
      { path: 'user-pwd', component: UserPwd },
      // 文章分类的子路由规则
      { path: 'art-cate', component: ArtCate },
      // 文章列表的子路由规则
      { path: 'art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 只有后台主页需要访问权限
  if (to.path === '/') {
    const token = localStorage.getItem('token')
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
